package com.fudan.backend.controller;


import com.fudan.backend.controller.enums.ReturnCode;
import com.fudan.backend.pojo.statics.UserRole;
import com.fudan.backend.exception.RetCode;
import com.fudan.backend.util.JwtUtil;
import com.fudan.backend.util.R;
import com.fudan.backend.pojo.User;
import com.fudan.backend.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

//    @Autowired
//    private RedisUtil redisUtil;

    @GetMapping("/info/{userId}")
    public R getUserByUserId(@PathVariable String userId, @RequestHeader String token) {
        User user = userService.getUserByUserId(userId);
//        String id = redisUtil.get(token);
        String id = JwtUtil.getUserId(token);
        //token无效或非管理员且用户id不匹配
        if (id == null || (!id.equals(userId) && JwtUtil.getRole(token) != UserRole.Admin)) {
            return new R(RetCode.UNAUTHORIZED_REQUEST.getCode(), RetCode.UNAUTHORIZED_REQUEST.getMessage());
        }

        if (user == null) {
            return new R(RetCode.USERNAME_ERROR.getCode(), RetCode.USERNAME_ERROR.getMessage());
        }

        return new R(RetCode.USER_SUCCESS.getCode(), RetCode.USER_SUCCESS.getMessage(), RetCode.USER_SUCCESS.getMessage(), user);
    }

    @GetMapping("/info")
    public R getAllUser(int current, int size) {
        PageInfo<User> page = userService.getAllUserByPage(current, size);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userList", page.getList());
        map.put("total", page.getTotal());
        return new R(RetCode.USER_SUCCESS.getCode(), RetCode.USER_SUCCESS.getMessage(), RetCode.USER_SUCCESS.getMessage(), map);
    }

    @GetMapping("/login")
    public R login(String username, String password) {
        RetCode code = userService.login(username, password);
        if(code != RetCode.USER_SUCCESS) {
            return new R(ReturnCode.failure, code.getMessage());
        }

        HashMap<String, Object> map = new HashMap<>();
        User user = userService.getUserByUsername(username);
        String token = JwtUtil.createToken(user.getUserId(), user.getUsername(), user.getRole());
//        redisUtil.set(token, user.getUserId());
        map.put("userId", user.getUserId());
        map.put("role", user.getRole());
        map.put("token", token);
        return new R(RetCode.USER_SUCCESS.getCode(), RetCode.USER_SUCCESS.getMessage(), RetCode.USER_SUCCESS.getMessage(), map);
    }

    /**
     * 普通用户注册
     */
    @PostMapping("/register")
    public R signUp(@RequestBody User user) {
        //判断用户格式合法性
        RetCode formatCode = userService.checkUserFormat(user);
        if(formatCode != RetCode.USER_SUCCESS){
            return new R(formatCode.getCode(), formatCode.getMessage());
        }
        //不可注册管理员且角色不可为空
        if (user.getRole() == null || user.getRole() != UserRole.Seller && user.getRole() != UserRole.Buyer) {
            return new R(RetCode.UNAUTHORIZED_REQUEST.getCode(), RetCode.UNAUTHORIZED_REQUEST.getMessage());
        }
        RetCode retCode = userService.signUp(user);
        return new R(retCode.getCode(), retCode.getMessage());
    }

    @PostMapping("/info/modify/password")
    public R changePassword(@RequestBody Map<String, Object> map, @RequestHeader String token){
        String userId = null;
        String oldPassword = null;
        String newPassword = null;
        try{
            userId = map.get("userId").toString();
            oldPassword = map.get("oldPassword").toString();
            newPassword = map.get("newPassword").toString();
        }
        catch(Exception e){
            return new R(RetCode.INVALID_REQUEST.getCode(), RetCode.INVALID_REQUEST.getMessage());
        }
        String tokenUserId = JwtUtil.getUserId(token);
        if(!userId.equals(tokenUserId)){
            return new R(RetCode.UNAUTHORIZED_REQUEST.getCode(), RetCode.UNAUTHORIZED_REQUEST.getMessage());
        }
        RetCode retCode = userService.changePassword(userId, oldPassword, newPassword);
        return new R(retCode.getCode(), retCode.getMessage());
    }

    @PostMapping("/info/modify")
    public R modifyUserInfo(@RequestBody User user, @RequestHeader String token){

        String tokenUserId = JwtUtil.getUserId(token);
        if(user == null || !user.getUserId().equals(tokenUserId)){
            return new R(RetCode.UNAUTHORIZED_REQUEST.getCode(), RetCode.UNAUTHORIZED_REQUEST.getMessage());
        }
        RetCode retCode = userService.updateUserInfo(user);
        return new R(retCode.getCode(), retCode.getMessage());
    }
}
